/**
 * Created on 15/7/13.
 */
$(function() {
    function openErrorModal() {
        var modalElem = $(".modal-error");
        if(modalElem.length > 0) {
            modalElem.show();
        } else {
            var modal = '<div class="modal-error">' +
                '<div class="modal-content">' +
                '<div class="modal-title">登录失败，是否找回密码</div>' +
                '<div class="modal-btns">' +
                '<div class="modal-cancel">取消</div>' +
                '<div class="modal-submit">找回密码</div>' +
                '</div>' +
                '</div>' +
                '</div>'
            $("body").append(modal);
        }

        $(".modal-cancel").on("click", function() {
            $(".modal-error").hide();
        });

        $(".modal-submit").on("click", function() {
            window.location.href="/web/findpwd";
        });
    }

    $(".submit").on("click", function(e) {
        e.preventDefault();

        var phone = $("#phone").val();
        var passwd = $("#passwd").val();

        var phone_re = /^0\d{2,3}\d{7,8}$|^1[3578]\d{9}$|^147\d{8}$/;
        if(!phone_re.test(phone)) {
            $(".error-c").html("请输入正确的手机号码");
            return;
        }

        var pass_re = /^\S{6,20}$/;
        if(!pass_re.test(passwd)) {
            $(".error-c").html("请输入6-20位密码");
            return;
        }

        var signinUrl = "/api/user/signin";

        $.ajax({
            url: signinUrl,
            data: {
                postData: JSON.stringify({
                idx: 0,
                params: {
                    from: "phone",
                    phone: phone,
                    passwd: md5(passwd, "Sk4Ys7sPTx+gT5ssPHXV4ieKwPMKB0czjb+2rVfICMo=")
                    }
                })
            },
            type: "post",
            dataType: "json",
            success: function(res) {
                if(res.ret == 0) {
                    window.location.href='/web/topic/list';
                } else {
                    openErrorModal();
                }
            },
            error: function(res) {
                console.log(res)
            }
        });
    });

    $(".submit-problem").on("click", function(e) {
        e.preventDefault();

        var menuElem = $(".menu-problem");

        if(menuElem.length > 0) {
            menuElem.show();
        } else {
            var menuProblem = '<div class="menu-problem">' +
                '<div class="menu-content">' +
                '<div class="menu-submit"><div class="menu-btn-inner">找回密码</div></div>' +
                '<div class="menu-cancel"><div class="menu-btn-inner">取消</div></div>' +
                '</div>' +
                '</div>';

            $("body").append(menuProblem);
        }

        $(".menu-submit").on("click", function(e) {
            window.location.href="/web/findpwd";
        });

        $(".menu-cancel").on("click", function(e) {
            $(".menu-problem").hide();
        })
    });
});
